package fm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.*;

import org.eclipse.jetty.server.Request;
/* possibly used
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.NCSARequestLog;
import javax.servlet.http.HttpServlet;
* */


public class Main {



    public static void main(String[] args) {
        /*
        move the following out of the Main class
        * */
        class HelloHandler extends AbstractHandler
        {
            public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
                    throws IOException, ServletException
            {
                System.out.println(request.getMethod());
                response.setContentType("text/html;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getWriter().println("<h1>Hello World</h1>");
            }
        }
        System.out.println("hello");
        Connection conn = null;
        try {
            Class.forName("org.postgresql.Driver").newInstance();
            System.out.println("postgresql JDBC Driver Registered!");
            conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mooc",
                    "fox", "iLovepg");
            // do sth
            conn.close();

            Server server = new Server(8080);
            server.setHandler(new HelloHandler());
            server.start();
            server.join();


        } catch (ClassNotFoundException e) {
        //Cannot register postgresql  driver
            // System.out.println("This is something you have not add in postgresql library to classpath!");
            e.printStackTrace();
        } catch (Exception ex) {
// handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ((SQLException) ex).getSQLState());
//System.out.println("VendorError: " + ex.getErrorCode());
        }

    }

}
